package com.code.exam.service.impl;


import com.code.exam.dto.AdminLoginDTO;
import com.code.exam.dto.CgPasswordDTO;
import com.code.exam.dto.UserLoginDTO;
import com.code.exam.dto.UserRegisterDTO;
import com.code.exam.entity.Admin;
import com.code.exam.entity.CgPassword;
import com.code.exam.entity.User;
import com.code.exam.mapper.AdminMapper;
import com.code.exam.mapper.UserMapper;
import com.code.exam.service.AdminService;
import com.code.exam.service.UserService;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;


    /**
     * 管理员登录
     *
     * @param userLoginDTO
     * @return
     */
    public User login(UserLoginDTO userLoginDTO) {
        String username = userLoginDTO.getUsername();
        String password = userLoginDTO.getPassword();

        User user = userMapper.getByUsername(username);

        //处理异常状况（密码错误，用户不存在）
        if(user == null){
            //用户不存在
            throw new RuntimeException("用户不存在");
        }
        if(!user.getPassword().equals(password)){
            //密码错误
            throw new RuntimeException("密码错误");
        }

        //返回实体对象
        return user;
    }


    public String register(User user) {
        String username = user.getUsername();
        User user1 = userMapper.getByUsername(username);
        if(user1 != null)
        {
            throw new RuntimeException("用户名已存在");
        }
        else{
              userMapper.register(user);
        }
        return username;
    }


    public void changepassword(Long userId, CgPasswordDTO cgPasswordDTO){
        User user = userMapper.getById(userId);
        CgPassword cgPassword = new CgPassword();
        BeanUtils.copyProperties(cgPasswordDTO,cgPassword);
        if(! cgPassword.getOldPassword().equals(user.getPassword())){
            new RuntimeException("旧密码错误");
        }
        else{
            userMapper.changepassword(cgPassword.getNewPassword(),userId);
        }

    }
}
